import re
from typing import List, Optional, Tuple


def extract_code_block(markdown_string: str) -> Optional[str]:
    """
    Extract the code block from the markdown string.

    Args:
        markdown_string: The markdown string to extract the code block from.

    Returns:
        The code block from the markdown string.
    """
    pattern = r"```[a-zA-Z]*\n([\s\S]*?)\n```"  # 匹配 ```code``` 格式的代码块
    match = re.search(pattern, markdown_string)
    if match:
        code_block = match.group(1)
        return code_block.strip()  # 返回去掉首尾空白字符的代码块
    else:
        return None


def extract_code_blocks(markdown_string: str) -> List[str]:
    """
    Extract all the code blocks from the markdown string.

    Args:
        markdown_string: The markdown string to extract the code blocks from.

    Returns:
        A list of code blocks from the markdown string.
    """
    pattern = r"```[a-zA-Z]*\n([\s\S]*?)\n```"  # 匹配 ```code``` 格式的代码块
    matches = re.findall(pattern, markdown_string)
    return [match.strip() for match in matches]


def extract_code_blocks_with_language(markdown_string: str) -> List[Tuple[str, str]]:
    """
    Extract all the code blocks with language from the markdown string.

    Args:
        markdown_string: The markdown string to extract the code blocks with language from.

    Returns:
        A list of code blocks with language from the markdown string.
    """
    code_blocks = []
    block = None
    lang = None
    for line in markdown_string.splitlines():
        if m := re.match(r"\s*```([a-zA-Z]*)$", line):
            if block is not None:
                code_blocks.append((lang, block))
                block = None
                lang = None
            else:
                lang = m.group(1)
                block = ""
        else:
            if block is not None:
                block += line + "\n"

    return code_blocks


def contains_chinese(text: str) -> bool:
    """
    Check if the text contains Chinese characters.

    Args:
        text: The text to check for Chinese characters.

    Returns:
        True if the text contains Chinese characters, False otherwise.
    """
    pattern = re.compile(r"[\u4e00-\u9fff]")  # Unicode range for Chinese characters
    return bool(pattern.search(text))
